<?php

namespace WXAPI\Controller;

use Think\Log;
use WXAPI\Logic\WxsendLogic;
class LiveController extends BaseController
{

    public function live_room_list()
    {
        $page = I('page', 1);
        $limit = I('limit', 20);
        if ($page == 1) {
            $page = 0;
        } else {
            $page = $page - 1;
        }
        $showPage = $page * $limit;
        $where = [];
        $where['dataflag'] = 1;
        $list = M('live')->where($where)->limit($showPage,$limit)->order('id desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
        }
        $data = array('code' => 1, 'msg' => '获取成功', 'data' =>['data'=>$list]);
        exit(json_encode($data));
    }

    public function get_live_goods()
    {
        $page = I('page', 1);
        $limit = I('limit', 2000);
        $live_id = I('live_id');
        if ($page == 1) {
            $page = 0;
        } else {
            $page = $page - 1;
        }
        $showPage = $page * $limit;

        $goods_list =  M('live_goods a')
            ->field('b.floating,b.store_id,b.prom_id,b.shop_price,b.goods_name,b.original_img,b.goods_id,b.shop_price,b.goods_remark,c.store_name,a.*')
            ->join('ty_goods b ON a.goods_id = b.goods_id','left')
            ->join('ty_store c ON b.store_id = c.store_id','left')
            ->where(['live_id'=>$live_id])->limit($showPage,$limit)->order('a.number asc')->select();
        foreach ($goods_list as $key=>$value){
            $goods_list[$key]['original_img'] = C('MYOSS')['url'].$value['original_img'];
            $quyu_price=quyu_price($this->fenbu_id,$value['store_id']);
            $goods_list[$key]['image'] = C('MYOSS')['url'].$value['original_img'];
            $goods_list[$key]['shop_price'] = geshi($value['shop_price']*($value['floating']/100)*$quyu_price);//浮点计算

            $goods_list[$key]['shop_price'] +=yj_price($value['goods_id'],$goods_list[$key]['shop_price'],$this->fenbu_id);

            $goods_list[$key]['shop_price'] = geshi($goods_list[$key]['shop_price']);
            $goods_list[$key]['status_status']=0;
            // 商品分类页优惠折扣显示 20181129 亮 START
            if (($value['prom_id'] >0) && $value['prom_id']){
                $prom_goods = M('prom_goods')->where(array('id'=>$value['prom_id']))->find();
                $prom_code = C('MYOSS')['url'].$prom_goods['prom_code'];

                $datass = time();
                if (($datass > $prom_goods['start_time']) && ($datass < $prom_goods['end_time'])){
                    $statusss = 1;
                    if ($prom_goods['type'] == 0){
                        $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                        $prom_goods_content = 0;
                    }elseif($prom_goods['type'] == 1){
                        $prom_goods_price = $goods_list[$key]['shop_price'] - $prom_goods['expression'];
                        $prom_goods_content = 0;
                    }elseif($prom_goods['type'] == 2){
                        $prom_goods_price = $prom_goods['expression'];
                        $prom_goods_content = 0;
                    }elseif($prom_goods['type'] == 5){
                        $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                        $prom_goods_content = 0;
                    }else{
                        $prom_goods_price = $goods_list[$key]['shop_price'];
                        $prom_goods_content = "购买赠送代金券$prom_goods[expression]元";
                    }
                    $goods_list[$key]['expression'] =$prom_goods['expression'];
                    $goods_list[$key]['expressions'] =huodong_name($prom_goods['type'],$prom_goods['expression']);//'活动！'.str_replace("0","",$prom_goods['expression']).'折';
                    $goods_list[$key]['prom_goods_price'] = $prom_goods_price;
                    $goods_list[$key]['prom_goods_content'] = $prom_goods_content;
                    $goods_list[$key]['prom_code'] = $prom_code;
                    $goods_list[$key]['status_status'] = $statusss;
                }
            }
        }
        $data = array('code' => 1, 'msg' => '获取成功', 'data' =>['data'=>$goods_list]);
        exit(json_encode($data));
    }

    public function add_msg()
    {
        $msg = I('msg');
        $user_id = I('user_id');
        $live_id = I('live_id');
        $time  = date('Y-m-d H:i:s',time());
        M('live_msg')->add(['msg'=>$msg,'live_id'=>$live_id,'user_id'=>$user_id,'create_time'=>$time]);
        $data = array('code' => 1, 'msg' => '添加成功', 'data' =>['data'=>[]]);
        exit(json_encode($data));
    }

    public function msg_list()
    {
        $live_id = I('live_id');
        $live_msg = M('live_msg a')->field('b.company,a.msg')->join('ty_users as b ON a.user_id = b.user_id','left')->where(['live_id'=>$live_id])->order('id desc')->limit(100)->select();
        $live_msg = array_reverse($live_msg);
        $data = array('code' => 1, 'msg' => '获取成功', 'data' =>['data'=>$live_msg]);
        exit(json_encode($data));
    }

    public function live_list()
    {
//        $store_id = I('store_id');
//        $cPage = I('cPage');
//
//        $cPage = $cPage * 30;
//        getWechatLive($store_id);
//        $where = "dataflag = 1 and store_id=".$store_id;
//        $list = M('live')->where($where)->order('roomid desc')->limit($cPage,15)->select();
//        foreach ($list as $key=>$item){
////            $list[$key]['live_status'] = C('WECHAT_LIVE_STATUS')[$item['live_status']];
//            $list[$key]['goods'] =  json_decode($item['goods'],true);
//        }
//        exit(jsonReturn(1,'获取成功',$list));
    }


    public function video_list()
    {
        $store_id = I('store_id');
        $cPage = I('cPage');

        $cPage = $cPage * 30;
        $where = "dataflag = 1 and store_id=".$store_id;
        $list = M('video')->where($where)->order('sort desc')->limit($cPage,15)->select();
        $store = M('store')->where(['store_id'=>$store_id])->find();
        foreach ($list as $key=>$item){
//            $list[$key]['live_status'] = C('WECHAT_LIVE_STATUS')[$item['live_status']];
            $list[$key]['share_img'] = C('MYOSS')['url'].$item['share_img'];
            $list[$key]['finder_user'] = $store['finder_user'];
            $list[$key]['start_time'] = date('Y-m-d H:i:s',$item['start_time']);
        }
        exit(jsonReturn(1,'获取成功',$list));
    }

    public function video_info()
    {
        $id = I('id');
        $store_id = I('store_id');
        $info = M('video')->where(['id'=>$id,'dataflag'=>1])->find();
        $store = M('store')->where(['store_id'=>$store_id])->find();
        if($info){
            $info['share_img'] = C('MYOSS')['url'].$info['share_img'];
            $info['finder_user'] = $store['finder_user'];
        }
        exit(jsonReturn(1,'获取成功',$info));
    }


    /**
     * 进入直播间记录
     * @return void
     */
    public function add_live_browse()
    {
        $id = I('id');
        $user_id = I('user_id');
        $browse = M('live_browse')->where(['live_id'=>$id,'user_id'=>$user_id])->find();
        if(!$browse){
            M('live_browse')->add(['live_id'=>$id,'user_id'=>$user_id,'create_time'=>date('Y-m-d H:i:s',time())]);
        }
        exit(jsonReturn(1,'添加成功',[]));
    }

    /**
     * 退出直播间记录
     * @return void
     */
    public function out_live_browse()
    {
        $id = I('id');
        $user_id = I('user_id');
        M('live_browse')->where(['live_id'=>$id,'user_id'=>$user_id])->delete();
        exit(jsonReturn(1,'删除成功',[]));
    }




    public function set_live_channels()
    {
        $data = I('');
        if(empty($data)){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
        }
        $store_id = $data['store_id'];
        $live_json = json_decode($data['live_json'],true);
        Log::record($data,'DEBUG');
        if($data){
            foreach ($live_json as $item){
                $channels = M('live_channels')->where(['nonceId'=>$item['nonceId']])->find();
                $attr = [
                    'description'=>$item['description'],
                    'headUrl'=>$item['headUrl'],
                    'nickname'=>$item['nickname'],
                    'playbackState'=>$item['playbackState'],
                    'replayStatus'=>$item['replayStatus'],
                    'status'=>$item['status'],
                    'store_id'=>$store_id,
                    'update_time'=>date('Y-m-d H:i:s',time()),
                ];
                $attr_add = [
                    'add_time'=>date('Y-m-d H:i:s',time()),
                    'feedId'=>$item['feedId'],
                    'nonceId'=>$item['nonceId']];
                if($channels){
                    M('live_channels')->where(['id'=>$channels['id']])->setField($attr);
                }else{
                    $data_add = array_merge($attr,$attr_add);
                    M('live_channels')->add($data_add);
                }
            }

            exit(jsonReturn(1,'上传直播成功',[]));
        }
    }

    public function live_channels_list()
    {
        $store_id = I('store_id');
        $cPage = I('cPage');

        $cPage = $cPage * 30;
        $where = "is_show = 1 and store_id=".$store_id;
        $list = M('live_channels')->where($where)->order('sort asc,id desc')->limit($cPage,15)->select();
        foreach ($list as $key=>$item){
            $list[$key]['live_status'] = C('WECHAT_CHANNELS_LIVE_STATUS')[$item['status']];
        }
        exit(jsonReturn(1,'获取成功',$list));
    }


    public function set_live_notice()
    {
        $data = I('');
        if(empty($data)){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
        }

        $store_id = $data['store_id'];
        $notice_id = $data['notice_id'];
        $user_id = $data['user_id'];
        $start_time = date('Y-m-d H:i',$data['start_time']);
        M('live_notice')->add(['store_id'=>$store_id,'notice_id'=>$notice_id,'user_id'=>$user_id,'start_time'=>$start_time]);

        exit(jsonReturn(1,'预约成功',[]));
    }

    public function get_live_notice()
    {
        $data = file_get_contents('php://input');
        $data = json_decode($data,true);

        $store_id = $data['store_id'];
        $notice_id = $data['notice_id'];
        $user_id = $data['user_id'];
        $live_notice = M('live_notice')->where(['store_id'=>$store_id,'notice_id'=>$notice_id,'user_id'=>$user_id])->find();
        $live_notice = $live_notice ? 1 : 0;
        exit(jsonReturn(1,'预约状态',['data'=>$live_notice]));
    }

    /**
     * 获取现在有没有可以预约的直播
     * */
    public function reservationLive(){
        $data = I('');
        if(empty($data)){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
        }
        $time = time();
        $reservationList = M('live')->where("reservation_status = 1 and live_status = 0 and start_time >$time")->order('sort asc,id desc')->find();

        if(!empty($reservationList)){
            $reservationList['share_img'] = C('MYOSS')['url'] .$reservationList['share_img'];
            $reservationList['start_time'] = date('Y-m-d H:i:s',$reservationList['start_time']);
            $status = M('live_reservation')->where(['live_id'=>$reservationList['id'],'member_id'=>$data['user_id']])->find();
            if(!empty($status)){
                $status = 0;
            }else{
                $status = 1;
            }
            $reservationList['status'] = $status;
        }else{
            $reservationList = [];
        }


        $json = [];
        $json['code'] = 1;
        $json['msg'] = '获取成功';
        $json['data'] = $reservationList;
        $this->ajaxReturn($json);
    }




    /**
     * 用户预约直播
     * */
    public function reservation_user(){
        $data = I('');
        if(empty($data)){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
        }
        $save['member_id'] = $data['user_id'];
        $save['status'] = 1;
        $save['add_time'] = time();
        $save['live_id'] = $data['live_id'];
        $info = M('live_reservation')->where(['live_id'=>$data['live_id'],'member_id'=>$data['user_id']])->find();
        if(!empty($info)){
            $json = [];
            $json['code'] = 0;
            $json['msg'] = '已经预约过';
            $json['data'] = [];
            $this->ajaxReturn($json);
        }
        M('live_reservation')->add($save);
        $json = [];
        $json['code'] = 1;
        $json['msg'] = '操作成功';
        $json['data'] = [];
        $this->ajaxReturn($json);
    }



    /**
     * 是否在开播
     * */
    public function detectionLive(){
        $data = I('');
        if(empty($data)){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
        }

        $liveInfo = M('live')->where("live_status = 1")->order('start_time desc')->find();
        if(empty($liveInfo)){
            $liveInfo = [];
        }else{
            $liveInfo['share_img'] = C('MYOSS')['url'] .$liveInfo['share_img'];
            $liveInfo['go_img'] = C('MYOSS')['url'] .$liveInfo['go_img'];
            $liveInfo['start_time'] = date('Y-m-d H:i:s',$liveInfo['start_time']);
        }



        $json = [];
        $json['code'] = 1;
        $json['msg'] = '获取成功';
        $json['data'] = $liveInfo;
        $this->ajaxReturn($json);
    }

    /**
     * 直播详情
     * */
    public function liveDetail(){
        $data = I('');
        if(empty($data)){
            $data = file_get_contents('php://input');
            $data = json_decode($data,true);
        }
        $id = $data['id'];
        $json = [];
        if(empty($id)){
            $json['code'] = 0;
            $json['msg'] = '获取失败';
            $json['data'] = [];
            $this->ajaxReturn($json);
        }
        $liveInfo = M('live')->where("id = $id")->find();
        $liveInfo['begin_time'] = $liveInfo['start_time']* 1000;
        $browse = M('live_browse')->where(['live_id'=>$id])->count();
        $liveInfo['share_img'] = C('MYOSS')['url'] .$liveInfo['share_img'];
        $liveInfo['start_time'] = date('Y-m-d H:i:s',$liveInfo['start_time']);
        $liveInfo['browse'] = $browse;
        $json['code'] = 1;
        $json['msg'] = '获取成功';
        $json['data'] = $liveInfo;
        $this->ajaxReturn($json);
    }


    /**
     * 发送直播提醒
     * */
    public function liveBroadcastReminder(){
        vendor('php-resque.autoload'); // 引入队列类库
        $job = '\\Common\\Job\\SendLiveMessageJob'; // 定义任务类
        \Resque::enqueue('SendLiveMessageJob', $job, [], true);
        // die;
        // $time = time();
        // $liveInfo = M('live')->where("live_status = 0 and start_time > $time")->select();

        // $Wxsend = new WxsendLogic();
        // foreach ($liveInfo as $k=>$v){

        //     if($v['start_time'] - $time > 0 && $v['start_time'] - $time < 3600 ){

        //         //把直播的预约人员拿出来发送订阅提醒
        //         $liveReservation = M('live_reservation r')
        //             ->field('r.*,u.open_id,l.name,l.start_time,l.anchor_name')
        //             ->join('ty_users u on u.user_id = r.member_id','left')
        //             ->join('ty_live l on l.id = r.live_id','left')
        //             ->where(['r.live_id'=>$v['id'],'r.wx_push'=>0])
        //             ->select();

        //             // dump($liveReservation);

        //         foreach ($liveReservation as $key=>$val){
        //             $sendData = [];
        //             $sendData['live_title'] = date('Y-m-d').'直播！';
        //             $sendData['live_name'] = $val['name'];
        //             $sendData['start_time'] = date('Y-m-d H:i:s',$val['start_time']);
        //             $sendData['live_member'] = $val['anchor_name'];
        //             $sendData['live_content'] = $val['name'];
        //             $sendData['live_id'] = $val['live_id'];
        //             M('live_reservation')->where(['member_id'=>$val['member_id'],'live_id'=>$val['live_id']])->save(['wx_push'=>1]);
        //             $push = $Wxsend->sendSubscribeMessage($val['open_id'], 8, '65vn03dHG4kyjGRkFleD4TTDGsa8gTSgCqeWZkTcKGc', $sendData);
        //             dump($push);

        //         }

        //     }

        // }
    }

    // /**
    //  * 测试发送
    //  * */
    // public function test(){
    //     $Wxsend = new WxsendLogic();
    //     $sendData = [];
    //     $sendData['live_title'] = date('Y-m-d').'直播！';
    //     $sendData['live_name'] = 'wo';
    //     $sendData['start_time'] = date('Y-m-d H:i:s',time());
    //     $sendData['live_member'] = '我';
    //     $sendData['live_content'] = '咩啊';
    //     $sendData['live_id'] = '14';

    //     $push = $Wxsend->sendSubscribeMessage('onTOt5Ply69CDJL1T6ZX_uTdSIIE', 8, '65vn03dHG4kyjGRkFleD4TTDGsa8gTSgCqeWZkTcKGc', $sendData);
    //     dump($push);
    // }



}